package com.windea.study.kotlin.jvm.crypt.sections

import java.security.*

object MessageDigestUtils {
	//32字节 64位 16进制字符串
	fun md5Digest(input: ByteArray) = digest(input, "MD5")
	
	//20字节 40位 16进制字符串
	fun sha1Digest(input: ByteArray) = digest(input, "SHA-1")
	
	//16字节 32位 16进制字符串
	fun sha256Digest(input: ByteArray) = digest(input, "SHA-256")
	
	private fun digest(input: ByteArray, algorithm: String): String {
		//得到实例
		val digest = MessageDigest.getInstance(algorithm)
		//进行数字签名
		val result = digest.digest(input)
		//转化成16进制字符串
		return result.toHexString()
	}
	
	private fun ByteArray.toHexString(): String {
		return this.joinToString("") {
			val hexString = Integer.toHexString(it.toInt() and 0xFF)
			if(hexString.length == 1) "0$hexString" else hexString
		}
	}
}
